<template>
	<div class="tui-conversation" @click="handleClickConv" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
		<view v-if="isShow==1||is_master==1">
			<TUISearch searchType="global" />
			<ConversationHeader v-if="isShowConversationHeader" ref="headerRef" />
		</view>

		
		<ConversationNetwork />
		<ConversationList class="tui-conversation-list" ref="conversationListDomRef"
			@handleSwitchConversation="handleSwitchConversation" @getPassingRef="getPassingRef"
			v-if="mobile=='23010310000'||mobile=='23010310001'||mobile=='23010310002'||mobile=='23010310003'||mobile=='23010310004'||mobile=='23010310005'||mobile=='23010310006'
			||mobile=='23010310007'||mobile=='23010310008'||mobile=='23010310009'||mobile=='23010310010'||mobile=='23010310011'||mobile=='23010310012'||mobile=='23010310013'" />
		<ConversationList1 class="tui-conversation-list" ref="conversationListDomRef"
			@handleSwitchConversation="handleSwitchConversation" @getPassingRef="getPassingRef" v-else />
	<vipPopup v-if="vipShow" :show="vipShow" />
	</div>
</template>


<script lang="ts">
	export default { 
		props:{
			isShow:{
				type:Number,
				default:0
			}
		},
		data() {
			return {
				iskf: null,
				to_mobile: null,
				type: null,
				vipShow:false,
				is_master:0
			}
		},
		onLoad(payload : any) {
			const that = this
			that.iskf = payload.iskf
			that.to_mobile = payload.to_mobile
			that.type = payload.type
			
			if(uni.getStorageSync('userInfoFull')){
				that.is_master = uni.getStorageSync('userInfoFull').user.is_master
			}
		},
		mounted() {
			
		}
	}
</script>
<script lang="ts" setup>
	import chatInterceptor from "@/common/chatInterceptor"
	import { visitChat } from "@/common/public"
	import {
		HTTP_REQUEST_URL,
		PERFIX,
		kfs,
		IM_SDKAppID
	} from '@/config/app';
	import TencentCloudChat from '@tencentcloud/chat';
	import { TUIStore, StoreName, TUIConversationService } from "@tencentcloud/chat-uikit-engine";
	import { ref, onMounted, reactive, onBeforeMount, getCurrentInstance, computed } from "../../adapter-vue";
	import { TUIGlobal } from "../../utils/universal-api/index";
	import ConversationList from "./conversation-list/index.vue";
	import ConversationList1 from "./conversation-list/indexlist.vue";
	import TUISearch from '../TUISearch/index.vue';
	import ConversationHeader from "./conversation-header/index.vue";
	import ConversationNetwork from "./conversation-network/index.vue";
	import { onHide } from "@dcloudio/uni-app"; // 该方法只能用在父组件内，子组件内不生效
	import store from '@/store/index.js';
	// #ifdef MP-WEIXIN
	import "./subPackage-init.ts";
	// #endif

	const emits = defineEmits(["handleSwitchConversation"]);
	const totalUnreadCount = ref(0);
	const headerRef = ref<HTMLElement | undefined>();
	const conversationListDomRef = ref<HTMLElement | undefined>();
	const touchX = ref<number>(0);
	const touchY = ref<number>(0);
	const isShowConversationHeader = ref<boolean>(true);

	const mobile = uni.getStorageSync('mobile');
	const chat = computed(() => { return store.state.im.chat });
	const getCurrent = getCurrentInstance();

	// #ifdef MP
	onMounted(() => {
		let isReady = chat.value.isReady();
		if (isReady) {
			toDetail();
		}
		chat.value.on(TencentCloudChat.EVENT.SDK_READY, function () {
			toDetail();
		});



	})
	// #endif
	if (mobile == '23010310000' || mobile == '23010310001' || mobile == '23010310002' || mobile == '23010310003' || mobile == '23010310004' || mobile == '23010310005' || mobile == '23010310006'
		|| mobile == '23010310007' || mobile == '23010310008' || mobile == '23010310009' || mobile == '23010310010' || mobile == '23010310011' || mobile == '23010310012' || mobile == '23010310013') {
		let chat1 = TencentCloudChat.create({
			SDKAppID: 1400818966 // Replace `0` with the `SDKAppID` of your Chat app during access.
		});
		let promise = chat1.logout();
		promise.then(function (imResponse) {
			console.log(imResponse.data); // 登出成功
		}).catch(function (imError) {
			console.warn('logout error:', imError);
		});
	}

	const toDetail = () => {
		const params = getCurrent.data;
		if (!params.to_mobile) {
			return
		}
		// 聊天的userID
		const userID = params.iskf === 'true' ? kfs[0] : PERFIX + params.to_mobile;
		const conversationID = `C2C${userID}`;
		TUIConversationService.getConversationProfile(conversationID)
			.then((res) => {
				console.log('createC2CConversation-success', res)
				TUIConversationService.switchConversation(
					res.data.conversation.conversationID
				);
				uni.navigateTo({
					url: '/TUIKit/components/TUIChat/index'
				});
			})
			.catch((err) => {
				// uni.showToast({
				// 	title: "The other party has not registered for a chat service",
				// 	icon: 'none'
				// })
				console.warn("打开会话失败", err.code, err.msg);
				
				const userID2 = kfs[0] ;
				const conversationID2 = `C2C${userID2}`;
				TUIConversationService.getConversationProfile(conversationID2)
					.then((res) => {
						console.log('createC2CConversation-success', res)
						TUIConversationService.switchConversation(
							res.data.conversation.conversationID
						);
						uni.navigateTo({
							url: '/TUIKit/components/TUIChat/index'
						});
					}).catch((err) => {
						console.warn("打开会话失败", err.code, err.msg);
					});
				
			});
	}
	TUIStore.watch(StoreName.CONV, {
		totalUnreadCount: (count : number) => {
			totalUnreadCount.value = count;
		},
	});

	TUIStore.watch(StoreName.CUSTOM, {
		isShowConversationHeader: (showStatus : boolean) => {
			isShowConversationHeader.value = showStatus !== false;
		},
	});
	

	const handleSwitchConversation = async (conversationID : string) => {
		
		// console.log("getCurrent",getCurrent);
		// 即时聊天权限与业务控制
		const interceptorRes = await chatInterceptor(getCurrent);
		// console.log("chatInterceptor",chatInterceptor);
		if (!interceptorRes) return;


		tj(conversationID)
		let lang = getApp().globalData.lang;
		if (lang == 'ru') {
			tj(conversationID)
			return;
		}

		uni.request({
			url: HTTP_REQUEST_URL + '/demo/mine',
			data: { mobile: mobile },
			header: {},
			success: (res) => {
				if (res) {
					if (res.data) {
						if (res.data.data) {
							if (res.data.data.level == 0) {

								uni.request({
									url: HTTP_REQUEST_URL + '/demo/message_score',
									data: { mobile: mobile },
									header: {},
									success: (r) => {
										if (r.data.data) {
											tj(conversationID)
										} else {
											uni.showModal({
												content: '您的权限不足哦!请联系工作人员!',
												showCancel: false,
												confirmText: '是',
											})
											return false;

										}
									},
								})

							} else {
								tj(conversationID)
							}
						}
					}
				}
			}
		})

	};


	const closeChildren = () => {
		headerRef?.value?.closeChildren();
		conversationListDomRef?.value?.closeChildren();
	};

	const handleClickConv = () => {
		closeChildren();
	};

	onHide(closeChildren);

	const handleTouchStart = (e : any) => {
		touchX.value = e.changedTouches[0].clientX;
		touchY.value = e.changedTouches[0].clientY;
	};

	const handleTouchEnd = (e : any) => {
		let x = e.changedTouches[0].clientX;
		let y = e.changedTouches[0].clientY;
		let turn = "";
		if (x - touchX.value > 50 && Math.abs(y - touchY.value) < 50) {
			//右滑
			turn = "right";
		} else if (x - touchX.value < -50 && Math.abs(y - touchY.value) < 50) {
			//左滑
			turn = "left";
		}
		if (y - touchY.value > 50 && Math.abs(x - touchX.value) < 50) {
			//下滑
			turn = "down";
		} else if (y - touchY.value < -50 && Math.abs(x - touchX.value) < 50) {
			//上滑
			turn = "up";
		}
		//根据方向进行操作
		if (turn === "down" || turn === "up") {
			closeChildren();
		}
	};

	const getPassingRef = (ref) => {
		ref.value = conversationListDomRef.value;
	}

	const tj = (conversationID) => {
		if (mobile == '23010310000' || mobile == '23010310001' || mobile == '23010310002' || mobile == '23010310003' || mobile == '23010310004' || mobile == '23010310005' || mobile == '23010310006'
			|| mobile == '23010310007' || mobile == '23010310008' || mobile == '23010310009' || mobile == '23010310010' || mobile == '23010310011' || mobile == '23010310012' || mobile == '23010310013') {
			let fruits = conversationID.split("C2Cgluz_");
			setTimeout(() => {
				// 使用uni.navigateTo进行页面跳转
				TUIGlobal?.navigateTo({
					url: "/TUIKit/components/TUIConversation/indexlist?mobile=" + fruits[1],
				});
			}, 1000); // 延迟5秒
		} else {
			setTimeout(() => {
				// 使用uni.navigateTo进行页面跳转
				TUIGlobal?.navigateTo({
					url: "/TUIKit/components/TUIChat/index",
				});
			}, 1000); // 延迟5秒
		}

		emits("handleSwitchConversation", conversationID);
	};
</script>

<style lang="scss" scoped src="./style/index.scss"></style>